package net.osin.sm2js

import net.osin.crypto.{Exchange, SM2, SM3}
import org.scalajs.dom
import org.scalajs.dom.document

import scala.scalajs.js.annotation.JSExportTopLevel

object SM2APP {
  def main(args: Array[String]): Unit = {
    println("Hello world!")
  }

  @JSExportTopLevel("addClickedMessage")
  def addClickedMessage(): Unit = {
    appendPar(document.body,"chickme", "You clicked the button!")
  }
  def appendPar(targetNode: dom.Node,id:String, text: String): Unit = {
    val parNode = document.getElementById(id)
    parNode.innerHTML = text
//    targetNode.appendChild(parNode)
  }
  def getValue(id:String) = {
    val parNode = document.getElementById(id)
    parNode.nodeValue
  }

  @JSExportTopLevel("onClickedbox1")
  def onClickedbox1(): Unit = {
    val str = sm2encrypt("","")
    appendPar(document.body, "encrypt1",str.toString)
  }
  @JSExportTopLevel("onClickedbox2")
  def onClickedbox2(): Unit = {
    appendPar(document.body, "encrypt2","clicked the button(2)!")
  }

  @JSExportTopLevel("onClickedbox3")
  def onClickedbox3(): Unit = {
    appendPar(document.body, "encrypt3",sm3hash("abc"))
  }

  def sm3hash(s:String)={
    Exchange.toHexFromBytes(SM3.hash(s.getBytes))
  }

  def sm2encrypt(key:String,data:String,enc_dec:String="")={
    val x = new SM2()
    val keys = x.generateKeyPair
    val pubKey = keys.getPublicKey
    val privKey = keys.getPrivateKey
    enc_dec match {
      case "enc" => x.encrypt("Hello World! Hello World! Hello World! Hello World! ", pubKey)
      case "dec" => x.decrypt( data.getBytes(), privKey)
      case _ => Array(0.toByte)
    }

  }

}
